#include "FileQt.h"

#include <QFile>
#include <QIODevice>
#include <QTextStream>
#include <QStringList>
#include <QRegExp>
#include <QObject>
#include <QDir>
#include <QByteArray>
#include <QTextCodec>
#include <QXmlStreamReader>
#include <QDebug>
#ifdef WIN32
#include <ActiveQt/QAxObject>
#endif

FileQt* FileQt::instance = NULL;
FileQt* FileQt::getInstance()
{
    if(NULL == FileQt::instance)
    {
        FileQt::instance = new FileQt();
    }
    return FileQt::instance;
}

void FileQt::Destroy()
{
	if(NULL!=FileQt::instance){
		delete FileQt::instance;
		FileQt::instance = NULL;
	}
}

FileQt::FileQt()
{
}

FileQt::~FileQt()
{
}

bool FileQt::readListInfo(QVector<QVector<QString> > &list,const QString path,QString _div)
{
    return readToVector(path,list,_div);
}

bool FileQt::readListInfo(QVector<QVector<QString> > &list,const QString path)
{
	return readToVector(path,list,"\\W+");
}

bool FileQt::readListInfo_dot(QVector<QVector<QString> > &list,const QString path)
{
	return readToVector(path,list,",");
}

bool FileQt::readListInfo(QVector<QString> &list,const QString path)
{
	return readToVector(path,list);
}

bool FileQt::readToVector(QString _file,QVector<QVector<QString> > &_lists, QString _div)
{
    #ifdef WIN32
    if (_file.contains(".xls", Qt::CaseInsensitive))
    {
        return readToVectorXLS(_file,_lists);
    }
    #endif
	QFile file(_file);
    if (!file.open(QFile::ReadOnly)) {
    	qDebug() << "conn't open file  " << _file << "!\n";
        return false;
    }else{
        QTextStream stream( &file );
        QString line;
        while ( !stream.atEnd() ) {
            line = stream.readLine();
            QStringList _strL = line.split(QRegExp(_div));
            // QStringList _strL = line.split(QRegExp(_div),QString::SkipEmptyParts);
            QVector<QString> _onev;
            for (int i = 0; i < _strL.size(); i++)
            {
            	_onev.push_back(_strL[i]);
            }
            _lists.push_back(_onev);
        }
        file.close();

        if (_lists.empty())
    	{
    		return false;
    	}else{
    		return true;
    	}
    }
}

bool FileQt::readToVector(QString _file, QVector<QString> &_lists)
{
	QFile file(_file);
    if (!file.open(QFile::ReadOnly))
    {
    	qDebug() << "conn't open file  " << _file << "!\n";
        return false;
    }else{
        QTextStream stream( &file );
        stream.setCodec("UTF-8"); //中文编码
        QString line;
        while ( !stream.atEnd() ) {
            line = stream.readLine();
            _lists.push_back(line);
        }
        file.close();

        if (_lists.empty())
    	{
    		return false;
    	}else{
    		return true;
    	}
    }
}

void FileQt::getAllFileName_dot(const QString directory, const QString extName, QStringList& fileNames)
{
    QDir _dir(directory);
    QStringList filters;
    filters << ("*."+extName);
    _dir.setNameFilters(filters);
    _dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    _dir.setSorting(QDir::Name);
    fileNames = _dir.entryList();
    qDebug() << fileNames << "\n";
}

void FileQt::getAllFileName(const QString& directory, const QString& extName, QStringList& fileNames)
{
    QDir _dir(directory);
    QStringList filters;
    filters << ("*."+extName);
    _dir.setNameFilters(filters);
    _dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    _dir.setSorting(QDir::Name);
    QStringList _files = _dir.entryList();
    for (int i = 0; i < _files.size(); i++)
    {
        fileNames << _files[i].left(_files[i].lastIndexOf("."));
    }
    qDebug() << fileNames << "\n";
}

void FileQt::getSubDir(const QString& directory, QStringList& subdirs)
{
    QDir _dir(directory);
    _dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    _dir.setSorting(QDir::Name);
    subdirs = _dir.entryList();
    qDebug() << subdirs << "\n";
}

bool FileQt::readToVectorXML(QString _file, QStringList elements, QVector<QString> &_lists)
{
    QFile inputFile(_file);
    if(!inputFile.open(QFile::ReadOnly))
    {
        qDebug() << "cann't create file: "<< _file <<"\n";
        return false;
    }
	 QByteArray data = inputFile.readAll();
    inputFile.close();

    QTextCodec *codec = QTextCodec::codecForHtml(data);
    QString str = codec->toUnicode(data);
    QXmlStreamReader reader(str);
    //reader.readNext();

    bool readF = false;
    while (!reader.atEnd()&&!reader.hasError())
    {
        reader.readNext();
        if (reader.error())
        {
            qDebug()<<reader.errorString()<<": "<<reader.name().toString()<<"\n";
            return false;
        } else{
            if (QXmlStreamReader::StartElement==reader.tokenType()
               && elements.contains(reader.name().toString()))
            {
                readF = true;
                continue;
            }
            if (QXmlStreamReader::EndElement==reader.tokenType()
                && elements.contains(reader.qualifiedName().toString()))
            {
                readF = false;
                continue;
            }
            if(readF){
                _lists.push_back(reader.text().toString());
            }
        }
    }
    return true;
}

bool FileQt::readToVectorXML(QString _file, QStringList elements, QVector<QVector<QString> > &_lists,QString _div)
{
    QVector<QString> _list;
    if(readToVectorXML(_file,elements,_list)){
        for (int i = 0; i < _list.size(); i++)
        {
            QStringList _linelist = _list[i].split(QRegExp(_div));
            QVector<QString> _linevect;
            for (int j = 0; j < _linelist.size(); j++)
            {
                _linevect << _linelist[j];
            }
            _lists.push_back(_linevect);
        }
        return true;
    }
    return false;
}

#ifdef WIN32
bool FileQt::readToVectorXLS(QString _file, QVector<QVector<QString> > &_lists, int sheet)
{
	if(sheet<=0)
	{
		return false;
	}
    QAxObject *excel = NULL;
    QAxObject *workbooks = NULL;
    QAxObject *workbook = NULL;

    excel = new QAxObject("Excel.Application");//连接Excel控件
    if (!excel) {
        qDebug()<< QObject::tr("error info: ") << QObject::tr("EXCEL object loss") <<"\n";
        return false;
    }
    excel->dynamicCall("SetVisible(bool)", false);//不显示窗体
    excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。

    workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
    workbook = workbooks->querySubObject("Open(QString, QVariant)", _file); //打开工作簿
	qDebug() << "workbooks size = " << workbook->querySubObject("WorkSheets")->property("Count").toInt() << "\n";
	if(sheet>workbook->querySubObject("WorkSheets")->property("Count").toInt()){
		delete workbook;
		workbook = NULL;
		delete workbooks;
		workbooks = NULL;
		delete excel;
		excel = NULL;
		return false;
	}
    QAxObject * worksheet = workbook->querySubObject("WorkSheets(int)", sheet);//打开第一个sheet

    QAxObject * usedrange = worksheet->querySubObject("UsedRange");//获取该sheet的使用范围对象
    int intRowStart = usedrange->property("Row").toInt();
    int intColStart = usedrange->property("Column").toInt();

    QAxObject * rows = usedrange->querySubObject("Rows");
    int intRows = rows->property("Count").toInt();

    QAxObject * columns = usedrange->querySubObject("Columns");
    int intCols = columns->property("Count").toInt();

    for (int i = intRowStart; i < intRowStart + intRows; i++)//row
    {
        QVector<QString> _onev;
        for (int j = intColStart; j < intColStart + intCols; j++)//column
        {
            // QAxObject * range = worksheet->querySubObject("Cells(QVariant,QVariant)", i, j ); //获取单元格
            // // qDebug() << i << j << range->property("Value");
            // _onev.push_back(range->property("Value").toString());

            _onev.push_back(
                worksheet->querySubObject("Cells(QVariant,QVariant)", i, j )->property("Value").toString());
        }
        _lists.push_back(_onev);
    }
    workbook->dynamicCall("Close()");//关闭工作簿
    excel->dynamicCall("Quit()");//关闭excel

    delete columns;
    columns = NULL;
    delete rows;
    rows = NULL;
    delete usedrange;
    usedrange = NULL;
    delete worksheet;
    worksheet = NULL;
    delete workbook;
    workbook = NULL;
    delete workbooks;
    workbooks = NULL;
    delete excel;
    excel = NULL;

    return true;
}
#endif

bool FileQt::writeListInfo(QVector<QString> list,const QString path)
{
    QFile f(path);
    if(!f.open(QFile::WriteOnly | QFile::Text))
        return false;

    QTextStream out(&f);

    out.setCodec("UTF-8"); //中文编码
    for (int i = 0; i < list.size(); i++)
    {
        out << QString(list[i]);
    }
    f.close();
    return true;
}
